<script lang="ts" setup>
import type { BookAddRequest, DeleteRequest } from '#/api/types';
import type { BookVO } from '#/api/types/books';

import { ref } from 'vue';

import { message, Modal } from 'ant-design-vue';

import { deleteBook, insertContentOfFile, updateBook } from '#/api/core/books';
import { router } from '#/router';
import BookDetail from '#/views/resources/books/book-detail.vue';

// 定义 Props 接口
interface Props {
  items: BookVO[];
  title: string;
}

defineOptions({
  name: 'BookList',
});

withDefaults(defineProps<Props>(), {
  items: () => [],
});

const emit = defineEmits(['callSearch']);
const bookDetailFlag = ref<boolean>(false);
const bookUploadFlag = ref<boolean>(false);
const optionType = ref<string>('update');
const currentBookId = ref<number>(0);
const currentFile = ref<File>();
let currentBook: BookAddRequest = {
  author: '',
  description: '',
  genre: '',
  publicationYear: '',
  title: '',
};

const editBook = (item: BookAddRequest) => {
  currentBook = item;
  bookDetailFlag.value = true;
};
const importBook = (bookId: number) => {
  bookUploadFlag.value = true;
  currentBookId.value = bookId;
};

const callSearch = () => {
  emit('callSearch'); // 触发事件
};

const handleUpdate = async (data: BookAddRequest) => {
  try {
    const updated = await updateBook(data); // 等待 Promise 解决
    if (updated) {
      callSearch();
    }
  } catch (error) {
    console.error('修改失败:', error);
  }
  bookDetailFlag.value = false;
};

const handleDelete = (data: number) => {
  // 使用 Ant Design 的 Modal 组件弹出删除确认框
  Modal.confirm({
    cancelText: '取消',
    content: '您确定要删除这本书吗？',
    okText: '确定',
    onOk: async () => {
      const deleteRequest: DeleteRequest = {
        id: data,
      };

      try {
        const deleted = await deleteBook(deleteRequest);
        if (deleted) {
          // 删除成功后调用搜索函数更新列表
          callSearch();
          message.success('书籍删除成功'); // 显示成功消息
        } else {
          // 删除失败的处理逻辑
          message.error('删除书籍失败，请稍后重试。'); // 显示失败消息
        }
      } catch {
        // 异常处理
        message.error('删除过程中发生错误，请稍后重试。'); // 显示错误消息
      }
    },
    title: '确认删除',
  });
};

const handleCancel = () => {
  bookUploadFlag.value = false;
  bookDetailFlag.value = false;
  optionType.value = '';
};

const handleUpload = async () => {
  if (currentFile.value && currentBookId.value) {
    try {
      const uploaded = await insertContentOfFile(
        currentFile.value as File,
        currentBookId.value,
      );
      if (uploaded) {
        currentFile.value = undefined;
        bookUploadFlag.value = false;
        message.success('文件上传成功'); // 显示成功消息
      } else {
        message.error('上传后处理失败');
      }
    } catch (error: any) {
      message.error(error.message); // 显示失败消息
    }
  } else {
    message.warning('请先选择文件再上传。'); // 提示用户选择文件
  }
};

const handleCustomRequest = async ({ file: uploadFile }) => {
  currentFile.value = uploadFile;
};

const viewBook = (bookId: number, title: string) => {
  // 使用 router.push 方法导航到新路由
  router.push({
    path: '/resources/books/book-view',
    query: {
      bookId, // 传入所需的 bookId
      title, // 传入所需的 title
    },
  });
};
</script>

<template>
  <!-- <div class="title">{{ title }}</div> -->
  <a-list :data-source="items" item-layout="horizontal">
    <template #renderItem="{ item }">
      <a-list-item>
        <a-list-item-meta :description="item.description">
          <template #title>
            <a @click="viewBook(item.bookId, item.title)">
              {{ item.title }} - {{ item.author }}
            </a>
          </template>
          <template #avatar>
            <a-avatar src="https://joeschmoe.io/api/v1/random" />
          </template>
        </a-list-item-meta>
        <!-- 显示所有属性 -->
        <div class="item-details">
          <p><strong>作者:</strong> {{ item.author }}</p>
          <p><strong>体裁:</strong> {{ item.genre }}</p>
          <p><strong>出版时间:</strong> {{ item.publicationYear }}</p>
        </div>
        <div class="detail-button">
          <a-button type="primary" @click="editBook(item)"> 编辑 </a-button>
          <a-button danger type="primary" @click="handleDelete(item.bookId)">
            删除
          </a-button>
          <a-button @click="importBook(item.bookId)"> 导入 </a-button>
        </div>
        <BookDetail
          v-model:open="bookDetailFlag"
          :initial-data="currentBook"
          :option-type="optionType"
          @cancel="handleCancel"
          @update="handleUpdate"
        />
      </a-list-item>
    </template>
  </a-list>
  <a-modal
    v-model:visible="bookUploadFlag"
    title="上传文件"
    @cancel="handleCancel"
    @ok="handleUpload"
  >
    <a-upload :custom-request="handleCustomRequest" :show-upload-list="true">
      <a-button>选择文件</a-button>
    </a-upload>
  </a-modal>
</template>

<style scoped>
.item-details {
  display: flex;
  flex-wrap: wrap;
  margin-top: 8px;
  margin-right: 20px;
  font-size: 14px;
  color: #555;
}

.detail-button {
  display: flex;
  flex-wrap: wrap;
  margin-top: 8px;
  font-size: 14px;
  color: #c6adad;
}

.item-details p {
  margin-left: 10px;
}
.item-details strong {
  color: #4d7186;
}
</style>
